#!/usr/bin/python3
"""_summary_

    Returns:
        _type_: _description_
"""
# -*- coding:utf-8 -*-
#
# File Name:
# @Author:  paddy
# @Email:   3988263@qq.com
# @Time:    ${DATE} ${TIME}
# Project: ${PROJECT_NAME}
# ---------------------说明--------------------------
#
# ---------------------------------------------------
import logging
import os
import json

logger = logging.getLogger(__name__)
console = logging.StreamHandler()
console.setLevel(logging.INFO)
logger.addHandler(console)


class MyBase:
    """被继承的基础类
       主要包括将设备和组的数据在线读取到本地

    Returns:
        _type_: _description_
    """
    # 本地的业务组数据
    local_asset_data = None
    # 本地的设备模型
    local_device_module = None
    # 读取业务返回结果
    business = None
    # 在线中的设备列表
    device_array = []
    # 查询业务下分组（包含子分组）下拉结果
    asset_group = []

    def __init__(self, webapi):
        self.root_path = os.path.dirname(
            os.path.dirname(os.path.abspath(__file__))
            )
        self.webapi = webapi

    def load_entrying(self):
        """ 获取在线的所有数据，业务，组和设备
        """
        self.get_business_data()
        self._getbusiness_asset_id()
        self.load_online_asset_device()

    @property
    def local_business_name(self):
        """从本地加载项目名称

        Returns:
            _type_: _description_
        """
        _business_file = self.root_path+'/conf/data/business.json'
        with open(_business_file, 'rt', encoding='utf-8') as file:
            business_data = json.load(file)
        return business_data["name"]

    def _load_device_module(self):
        """读取本地的device_module.json
        """
        _device_modules_file = self.root_path+'/conf/data/device_module.json'
        with open(_device_modules_file, 'rt', encoding='utf-8') as file:
            self.local_device_module = json.load(file)

    # 本地加载asset_modules.json
    def _load_asset_modules(self):
        """_summary_
        """
        _asset_modules_file = self.root_path+'/conf/data/asset_module.json'
        with open(str(_asset_modules_file), 'rt', encoding='utf-8') as file:
            self.local_asset_data = json.load(file)

    def get_business_data(self):
        """读取业务返回的结果

        Returns:
            _type_: _description_
        """
        data = {
            "name": self.local_business_name,
            "limit": 1,
            "page": 1
        }
        status_code, message = self.webapi.api_business_index(data)
        if status_code == 200:
            if len(message['data']['data']) > 0:
                self.business = message['data']['data'][0]
        else:
            logger.error(message)

    def set_business_data(self, data):
        """将增加业务的操作返回结果配置为self.business

        Args:
            data (_type_): _description_
        """
        self.business = data

    def _getbusiness_asset_id(self):
        """查询业务根的组id,为了创建下一级组使用
        """
        if self.business is None:
            self.get_business_data()
        data = {
            "business_id": self.business['id']
        }
        status_code, message = self.webapi.api_asset_list_d(data)
        if status_code == 200:
            self.business['asset_id'] = message['data'][0]['id']
            logger.info(message['data'][0])

    def check_ishave_data(self):
        """判断是否有数据,如果有返回true

        Returns:
            _type_: _description_
        """
        result = False
        data = {
            "name": self.local_business_name,
            "limit": 0,
            "page": 0
        }
        status_code, message = self.webapi.api_business_index(data)
        if status_code == 200:
            result = len(message['data']['data']) > 0
        else:
            logger.error(message)
        return result

    def load_online_asset_device(self):
        """获取在线中的组和设备
        """

        data = {
            "current_page": 1,
            "per_page": 20,
            "device_id": "",
            "business_id": "",
            "asset_id": "",
            "device_type": "",
            "token": ""
        }
        status_code, message = self.webapi.api_device_list(data)
        if status_code == 200:
            self.device_array = message['data']['data']
        else:
            logger.error(message)

        data = {
            "business_id": self.business['id']

        }
        status_code, message = self.webapi.api_asset_list_d(data)
        if status_code == 200:
            self.asset_group = message['data']
        else:
            logger.error(message)

    @property
    def get_device_array(self):
        """返回在线设备的返回结果
        Returns:
            _type_: _description_
        """
        return self.device_array

    @property
    def get_business(self):
        """读取self.busines

        Returns:
            _type_: _description_
        """
        return self.business
